//
//  Status.m
//  OC-LBWeibo
//
//  Created by 李博 on 15/7/13.
//  Copyright © 2015年 libo. All rights reserved.
//

#import "Status.h"
#import "UserAccount.h"
#import "NetworkTools.h"
#import "UIImageView+WebCache.h"

#define WB_Home_Timeline_URL @"2/statuses/home_timeline.json"

@interface Status()

@property(nonatomic,strong)NSArray *properties;

@end

@implementation Status


///加载数据
+ (void)loadStatusInfoWithSinceId:(int)since_id maxId:(int)max_id finished:(void (^)(NSArray *, NSError *))finished
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:[UserAccount sharedUserAccount].access_token forKey:@"access_token"];
    
    if (since_id > 0) {
        NSString *sinceId = [NSString stringWithFormat:@"%d",since_id];
        [params setValue:sinceId forKey:@"since_id"];
    }
    if (max_id > 0) {
        NSString *maxId = [NSString stringWithFormat:@"%d",max_id];
        [params setValue:@"0" forKey:@"since_id"];
        [params setValue:maxId forKey:@"max_id"];

    }
    
    //发起网络请求
    [[NetworkTools sharedNetworkTools] GET:WB_Home_Timeline_URL parameters:params success:^(NSURLSessionDataTask *task, id JSON) {
        //从结果中取出微博数组
        NSArray *array = JSON[@"statuses"];
        if (array != nil) {
            //1. 获取微博的模型数组
            NSArray *list = [self statuses:array];
            // 缓存微博图片
            [self cacheWebImageStatusList:list finished:finished];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
}

+ (void)cacheWebImageStatusList:(NSArray *)list finished:(void (^)(NSArray *, NSError *))finished
{
    //1. 定义调度组
    dispatch_group_t group = dispatch_group_create();
    
    //2. 遍历数组
    for (Status *status in list) {
        if (status.pictureURLs == nil || status.pictureURLs.count == 0 ) {
            continue;
        }
        //进一步遍历pictureURLs数组，缓存图片
        for (NSURL *url in status.pictureURLs) {
            dispatch_group_enter(group);
            
            [[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                
                // 代码执行到此，说明图片已经被缓存完成
                NSLog(@"%@ %@",image,imageURL);
                
                //离开组
                dispatch_group_leave(group);
            }];
        }
    }
    
    //监听群组调度执行
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"缓存结束！！！");
        finished(list,nil);
    });
    

}


+ (NSArray *)statuses:(NSArray *)array
{
    
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        [arrayM addObject:[self statusWithDict:dict]];
    }
    return arrayM;
}


-(instancetype)initWithDict:(NSDictionary *)dict
{
    self = [super init];
    if (self) {
        //[self setValuesForKeysWithDictionary:dict];
        for (NSString *key in self.properties) {
            if (dict[key] == nil || [key  isEqual: @"user"] || [key  isEqual: @"retweeted_status"]){
                continue;
            }
            
            [self setValue:dict[key] forKey:key];
        }
        //判断字典中是否包含user
        NSDictionary * userDict = dict[@"user"];
        if(userDict){
            self.user = [User userWithDict:userDict];
        }
        //判断字典中是否包含 retweeted_status
        NSDictionary * retweetedDict = dict[@"retweeted_status"];
        if(retweetedDict){
            self.retweeted_status = [Status statusWithDict:retweetedDict];
        }
        
    }
    return self;
}


+(instancetype)statusWithDict:(NSDictionary *)dict
{
    return [[self alloc]initWithDict:dict];
}


- (NSString *)description
{
    NSDictionary *dict = [self dictionaryWithValuesForKeys:self.properties];
    
    return [NSString stringWithFormat:@"%@",dict];
}
- (NSArray *)properties
{
    if (_properties == nil) {
        _properties = @[@"created_at",@"id",@"text",@"source",@"pic_urls",@"user",@"retweeted_status"];
    }
    return _properties;
}


- (void)setPic_urls:(NSArray *)pic_urls
{
    _pic_urls = pic_urls;
    
    self.imageURLs = [NSMutableArray array];
    //self.largeImageURLs = [NSMutableArray array];
    
    for (NSDictionary *dict in _pic_urls) {
        //缩略图
        NSString *urlString = dict[@"thumbnail_pic"];
        [self.imageURLs addObject:[NSURL URLWithString:urlString]];
        //大图
//        urlString = [urlString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"large"];
//        [self.largeImageURLs addObject:[NSURL URLWithString:urlString]];

    }
    
}

- (NSMutableArray *)pictureURLs
{
    return self.retweeted_status != nil ? self.retweeted_status.imageURLs : self.imageURLs;
}
- (NSMutableArray *)largeImageURLs
{
    return self.retweeted_status != nil ? self.retweeted_status.largeImageURLs : self.largeImageURLs;
}

@end
